//
//  XKTabBar.swift
//  XK2WeiBo
//
//  Created by mac on 16/7/3.
//  Copyright © 2016年 陈肖坤. All rights reserved.
//

import UIKit

//声明协议
protocol XKTabBarDelegate:NSObjectProtocol {
    //声明协议方法
    func composeButtonClick()
}

class XKTabBar: UITabBar {

    //声明代理
    //使用weak修饰代理需要继承NSObjectProtocol 基协议
    weak var XKDelegate:XKTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //UITabBarButton 的宽度
        let width = SCREENW / 5
        
        //记录UITabBarButton 的标识
        var index:CGFloat = 0
        
        //通过遍历得到其子类身上的控件
        for value in self.subviews {
        
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
//                print(value)
                
                //设置宽度
                value.frame.size.width = width
                //设置X轴
                value.frame.origin.x = index * width
                
                index += 1
                
                //为了给撰写按钮添加位置
                if index == 2 {
                    index += 1
                }
            }
        }
        
        //设置撰写按钮frame
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
        
    }
    
    func setupUI() {
        addSubview(composeButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //监听方法 (如果私有后要加!@objc 防止找不到方法)
    @objc fileprivate func buttonClick() {
        XKDelegate?.composeButtonClick()
    }
    
    //撰写按钮
    fileprivate lazy var composeButton:UIButton = {
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: #selector(XKTabBar.buttonClick), for: UIControlEvents.touchUpInside)
        
        //设置背景image
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState())
        //设置image
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState())
        button.sizeToFit()
        
        return button
    }()
    

}
